package com.twd.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.ImmediateEventExecutor;

public class TextWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup group = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
            group.add(ctx.channel());
            // 新的连接
            for (Channel channel : group) {
                String message = ctx.channel().id().asShortText() + " 53453453...";
                channel.writeAndFlush(new TextWebSocketFrame(message));
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 客户端发送的文本
        String text = msg.text();
        // 构建Message
        String message = ctx.channel().id().asShortText()+text;

        // 广播所有客户端
        for (Channel channel : group) {
            channel.writeAndFlush(new TextWebSocketFrame(message));
        }
    }
}
